package com.golxen.framework.common.queue;


import com.golxen.utils.LogUtil;
import com.mysql.cj.util.LogUtils;
import org.slf4j.Logger;

import java.util.Comparator;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自动的可执行消息队列，能够自动驱动本队列中的指令有序执行
 */
public class AutoMQ<MsgType extends Runnable> implements IMQ<MsgType> {


	// 用于执行消息的线程池，需在队列初始化时指定
	private ExecutorService executorService = null;

	// 消息队列
	private Queue<MsgType> msgQueue = null;

	// 运行状态
	private boolean isRunning = false;

	/**
	 * 构造函数，使用非优先队列
	 * 
	 * @param executorService 消息执行线程池
	 */
	public AutoMQ(ExecutorService executorService) {
		this.executorService = executorService;
		this.msgQueue = new LinkedList<MsgType>();
	}

	public AutoMQ(ExecutorService executorService, Comparator<MsgType> comparator) {
		this.executorService = executorService;
		this.msgQueue = new PriorityQueue<MsgType>(10, comparator);
	}

	@Override
	public void add(MsgType msg) {
		synchronized (msgQueue) {
			msgQueue.add(msg);
			/* 原指令队列为空，提交到线程池推动指令执行 */
			if (msgQueue.size() != 0 && !isRunning) {
				if (!executorService.isShutdown()) {
					executorService.execute(msg);
					isRunning = true;
				}
			}
		}
	}

	@Override
	public void remove() {
		synchronized (msgQueue) {
			try {
				isRunning = false;
				if (msgQueue.size() > 0)
					msgQueue.remove();
				if (msgQueue.size() != 0) {
					// 修复异常
					if (!executorService.isShutdown()) {
						executorService.execute(msgQueue.peek());
						isRunning = true;
					}
				}
			} catch (Exception e) {
				LogUtil.COMMON.error("MsgQueue::remove:", e);
			}
		}
	}

	public void exec(MsgType type) {
		executorService.execute(type);
	}

	/**
	 * 清空所有消息
	 */
	@Override
	public void clear() {
		synchronized (msgQueue) {
			msgQueue.clear();
		}
	}

}
